package gsp420;

public class Threading implements Runnable
{
	int m_times;
	LinkedList<String> m_list;
	
	public void print()
	{
		LinkedList<String>.Node n = m_list.head;
		System.out.print("{");
		while(n != null)
		{
			System.out.print(n.data);
			n = n.next;
			if(n != null)System.out.print(", ");
		}
		System.out.println("}");
	}
	
	static boolean semaphoreOfTheList = false;
	
	public void battleRoyale()
	{
		// very bad semaphore
//		while(semaphoreOfTheList){}
//		semaphoreOfTheList = true;
		synchronized(m_list)
		{
//			print();
			String d = m_list.pop();
//			try{Thread.sleep(1);}catch(Exception e){}
			if(d != null)
			m_list.pushBack(d);
		}
//		semaphoreOfTheList = false;
	}
	public void run()
	{
		long start = System.currentTimeMillis();
		for(int i = 0; i < m_times; ++i)
			battleRoyale();
		long end = System.currentTimeMillis();
		System.out.println("took "+(end-start)+" ms");
	}
	public Threading(LinkedList<String> a_list, int a_times)
	{
		m_list = a_list;
		m_times = a_times;
	}
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.pushBack("Leonel");
		list.pushBack("Randy");
		list.pushBack("Kyle");
		list.pushBack("John");
		list.pushBack("Prof.V");
		int times = 1000;
		int threads = 50;
		Threading[] sample = new Threading[threads];
		Thread[] t = new Thread[sample.length];
		for(int i = 0; i < sample.length; i++)
		{
			sample[i] = new Threading(list, times);
			t[i] = new Thread(sample[i]);
		}
		for(int i = 0; i < sample.length; i++)
		{
			t[i].start();
		}
//		runInSequence(sample);
	}
	
	public static void runInSequence(Threading[] thread)
	{
		for(int i = 0; i < thread.length; ++i)
		{
			thread[i].run();
		}
	}
}
